<template>
  <view>
    <view class="wrap">
      <view class="u-tabs-box">
        <u-tabs-swiper
          ref="tabs"
          :list="list"
          :current="current"
          @change="change"
          :is-scroll="false"
          swiperWidth="750"
          active-color="#202E3C"
          inactive-color="#202E3C"
          font-size="30"
          bar-height="6"
          bar-width="40"
          :bar-style="bac"
          gutter="40"
          :offset="[2, -5]"
        ></u-tabs-swiper>
      </view>
      <u-modal
        v-model="showModel"
        @confirm="confirm"
        title="温馨提示"
        ref="uModal"
        :async-close="true"
        :content="showModelContent"
        show-cancel-button="true"
      ></u-modal>
      <swiper
        class="swiper-box"
        :current="swiperCurrent"
        @transition="transition"
        @animationfinish="animationfinish"
      >
        <!--       全部 -->
        <swiper-item class="swiper-item" v-for="(f, i) in list" :key="i">
          <scroll-view
            scroll-y
            style="height: 100%; width: 100%"
            :lower-threshold="10"
            class="scroll_wrapper"
          >
            <!--          加载显示  -->
            <view
              style="display: flex; justify-content: center; padding: 30rpx"
              v-if="show"
            >
              <u-loading mode="flower" :show="show"></u-loading>
            </view>
            <!--          无订单显示  -->
            <view
              style="display: flex; justify-content: center; padding: 30rpx"
              class="none_shopping"
              v-if="orderFilter.length === 0 && !show"
            >
              <image src="/static/None/None_shopping.png"></image>
              <text>暂无订单喔~</text>
            </view>
            <view
              class="order_wrapper"
              v-if="orderFilter && orderFilter.length && !show"
              v-for="(item, index) in orderFilter"
              :key="index"
              @tap.stop="orderToggle(item)"
            >
              <view class="title_wrapper">
                <view class="left_">
                  <image src="/static/order/2.png"></image>
                  <text>{{
                    item.orderType == 1
                      ? "普通订单"
                      : item.orderType == 2
                      ? "礼包订单"
                      : item.orderType == 3
                      ? "兑换订单"
                      : ""
                  }}</text>
                </view>
                <view class="right_">{{
                  item.refundOrder.status == "0"
                    ? "待审核"
                    : item.refundOrder.status == "1"
                    ? "待寄回"
                    : item.refundOrder.status == "2"
                    ? "售后中"
                    : item.refundOrder.status == "3"
                    ? "已完成"
                    : item.refundOrder.status == "4"
                    ? "驳回"
                    : ""
                }}</view>
              </view>
              <view class="order_info_wrapper">
                <image :src="httpUrlFn(item)"></image>
                <view class="right_wrapper">
                  <view class="item_1">
                    <view>{{ item.orderItems[0].prodName }}</view>
                    <view>￥{{ item.orderItems[0].price }}</view>
                  </view>
                  <!--                  <view class="item_2">-->
                  <!--                    <view>佣金:￥{{ item.commission }}</view>-->
                  <!--                  </view>-->
                  <view class="item_3">
                    <view>{{
                      item.orderItems[0].properties
                        .replace("{", "")
                        .replace("}", "")
                        .replace('"', "")
                        .replace(/"/gi, "")
                    }}</view>
                    <view>×{{ item.orderItems[0].quantity }}</view>
                  </view>
                </view>
              </view>
              <view class="money_wrapper">
                <view class="left_"
                  >售后类型：{{
                    item.refundOrder.refundType == 0
                      ? "退款"
                      : item.refundOrder.refundType == 1
                      ? "退货退款"
                      : item.refundOrder.refundType == 3
                      ? "换货"
                      : ""
                  }}</view
                >
                <view class="right_">
                  <view>共{{ item.orderItems[0].quantity }}件</view>
                  <view
                    >商品小计：<text
                      >￥{{ item.orderItems[0].productTotalAmount }}</text
                    ></view
                  >
                </view>
              </view>
              <view class="but_wrapper">
                <view>
                  <!--                待收货和已收货  -->
                  <view
                    class="logistics_"
                    v-if="item.refundOrder.status == '2'"
                    @tap.stop="logisticsFn(item, index)"
                    >查看物流</view
                  >
                  <view
                    class="delete_order_"
                    v-if="item.refundOrder.status == '3'"
                    @tap.stop="cancellationFn(item, index, '-1')"
                    >删除记录</view
                  >
                  <view
                    class="cancelRefund"
                    v-if="item.refundOrder.status == '0'"
                    @tap.stop="cancellationFn(item, index, '-3')"
                    >取消售后</view
                  >
                  <view
                    v-if="item.refundOrder.status == '1'"
                    class="expressDelivery_"
                    @tap.stop="expressDelivery(item, index, '1')"
                    >寄出快递</view
                  >
                  <view
                    v-if="item.refundOrder.status == '2'"
                    class="expressDelivery_"
                    @tap.stop="expressDelivery(item, index, '2')"
                    >修改快递单号</view
                  >
                </view>
              </view>
            </view>
            <u-loadmore
              v-if="orderFilter.length > 0 && !show"
              :status="status"
              :icon-type="iconType"
              :load-text="loadText"
              @loadmore="loadNextFn"
              class="loadmore_wrapper"
            />
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
    <u-modal
      v-model="showToggle"
      @confirm="confirmInfo"
      title="寄出快递"
      ref="uModal"
      show-cancel-button="true"
    >
      <view class="slot-content">
        <u-select
          v-model="showModal1"
          :list="expressCompanyList"
          @confirm="confirm1"
          class="input_select"
        ></u-select>
        <u-input
          v-model="formData.deliveryCompany"
          @click="showModal1 = true"
          :type="type"
          :select-open="showModal1"
          disabled="true"
          placeholder="请选择快递公司"
          border="true"
          class="input_wrapper"
        />
        <u-input
          v-model="formData.deliverySn"
          placeholder="请输入快递单号"
          border="true"
          class="input_wrapper"
        />
      </view>
    </u-modal>
  </view>
</template>

<script>
import {
  cancelApi,
  cancelDelete,
} from "@/api/orderApi";
import { BASE_URL_IMAHE } from "../../../../utils/https";
import { saveDelivery, selRefundOrder } from "@/api/selRefundOrder";

export default {
  watch: {
    swiperCurrent(newValue, oldValue) {
      this.order.size = 10;
      this.order.current = 1;
      this.orderFilter = [];
      this.myOrder();
      console.log(newValue, "新的");
      console.log(oldValue, "旧的");
    },
  },
  data() {
    return {
      type: "select",
      showModal1: false,
      //订单更新状态用
      orderUpdata: {},
      //原数组
      orderList: {
        records: [],
      },
      //用于条件渲染的数组
      orderFilter: [],
      bac: {
        background: "red",
      },
      status: "loadmore",
      iconType: "flower",
      loadText: {
        loadmore: "点击加载更多",
        loading: "正在加载，请喝杯茶...",
        nomore: "哼~😕我也是有底线的~",
        //哼~😕我也是有底线的~
        //😕我也是有底线的~
      },
      page: 0,
      pageSize: 10,
      show: false,
      list: [
        {
          name: "全部",
        },
        {
          name: "待审核",
        },
        {
          name: "待寄回",
        },
        {
          name: "售后中",
        },
        {
          name: "已完成",
        },
      ],
      orderType: [],
      // 因为内部的滑动机制限制，请将tabs组件和swiper组件的current用不同变量赋值
      current: 0, //tabs组件的current值，表示当前活动的tab选项
      swiperCurrent: 0, // swiper组件的current值，表示当前那个swiper-item是活动的
      tabsHeight: 0,
      dx: 0,
      showModel: false,
      showModelContent: "确定要取消订单吗？",
      options: null,
      order: {
        //页码
        current: 1,
        //条数
        size: 10,
        status: "", //退款状态，0 ->待审核；1 -> 待寄回；2 -> 售后中；3 ->已完成；4 -> 驳回
      },
      showToggle: false,
      formData: {
        orderSn: "",
        //售后编号
        afterSaleSn: "",
        //物流单号
        deliverySn: "",
        //快递公司
        deliveryCompany: "",
      },
      expressCompanyList: [
        {
          value: "1",
          label: "安能物流",
        },
        {
          value: "2",
          label: "安迅物流",
        },
        {
          value: "3",
          label: "平邮",
        },
        {
          value: "4",
          label: "百世汇通",
        },
        {
          value: "5",
          label: "德邦物流",
        },
        {
          value: "6",
          label: "顺丰快递",
        },
        {
          value: "7",
          label: "中通快递",
        },
        {
          value: "8",
          label: "韵达快递",
        },
      ],
      expressDeliveryList: {},
    };
  },
  onLoad(options) {
    console.log(options, "传递过来的");
    // 获取传递的对象参数，使用decodeURIComponent解码，并转为对象
    this.show = true;
    this.current = 0;
    this.swiperCurrent = 0;
    this.myOrder();
    console.log(this.swiperCurrent, "嘻嘻嘻");
  },
  onShow() {
    console.log("返回的");
  },
  //上拉
  onReachBottom() {
    console.log("触发上拉加载");
    //请求订单
    this.myOrder();
  },
  methods: {
    //b页面返回到a页面的参数
    otherFun(object) {
      if (object) {
        console.log(object);
        this.current = object.current;
        this.swiperCurrent =
          this.swiperCurrent === "" ? object.swiperCurrent : "";
      }
    },

    //点击订单详情
    orderToggle(item) {
      const data={
        ...item,
        ...item.refundOrder,
        ...item.orderItems[0]
      }
      console.log(item,'详情')
      uni.navigateTo({
        url: `/pages/subpackage/orderDetails/index?order=${encodeURIComponent(
          JSON.stringify(data)
        )}&status=2`,
      });
    },

    httpUrlFn(item) {
      if (item) {
        return BASE_URL_IMAHE + item.orderItems[0].pic;
      }
      return "";
    },


    //请求订单
    async myOrder() {
      this.status = "loading";
      //获取订单的状态
      this.order.status = this.swiperCurrent > 0 ? this.swiperCurrent - 1 : "";
      console.log(this.order.status, "status");
      const res = await selRefundOrder(this.order);
      console.log(res, "售后订单");
      if (res.code === 0 && res.data.records.length !== 0) {
        console.log("进来了");
        this.show = false;
        //保存原数组
        this.orderList = JSON.parse(JSON.stringify(res.data));

        //赋值到数组
        if (this.order.current === 1) {
          this.orderFilter = res.data.records;
        } else {
          this.orderFilter.push(
            ...JSON.parse(JSON.stringify(res.data.records))
          );
        }

        this.orderFilter.forEach((item) => {
          if (item.orderItems.length > 0) {
            item.orderType = item.orderItems[0].itemType;
          } else {
            item.orderType = "";
          }
          if (item.refundOrder) {
            item.itemType = item.refundOrder.status;
          } else {
            item.itemType = "";
          }
        });
        console.log(
          JSON.parse(JSON.stringify(this.orderFilter)),
          "orderFilter"
        );

        if (res.data.records.length === 0) {
          setTimeout(() => {
            this.status = "nomore";
          }, 800);
          return;
        }

        if (res.data.records && res.data.records.length >= this.order.size) {
          this.order.current++;
          setTimeout(() => {
            this.status = "loadmore";
          }, 800);
          return;
        }

        if (this.orderFilter.length <= this.order.size) {
          this.order.current++;
          setTimeout(() => {
            this.status = "loadmore";
          }, 800);
        } else if (
          res.data.records.length !== 0 &&
          res.data.records.length < this.order.size
        ) {
          this.order.current++;
          setTimeout(() => {
            this.status = "loadmore";
          }, 800);
          return;
        }
      } else {
        this.show = false;
        setTimeout(() => {
          this.status = "nomore";
        }, 800);
      }
    },

    //点击组件触发上拉加载
    loadNextFn() {
      console.log("点击组件触发上拉加载2123");
      //请求订单
      this.myOrder();
    },
    // tab栏切换
    change(index) {
      console.log(index, "tab切换");
      this.swiperCurrent = index;
      //切换状态重新请求
      // this.myOrder()
    },
    // swiper-item左右移动，通知tabs的滑块跟随移动
    transition({ detail: { dx } }) {
      this.$refs.tabs.setDx(dx);
    },
    // 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
    // swiper滑动结束，分别设置tabs和swiper的状态
    animationfinish({ detail: { current } }) {
      console.log(current, "位置索引");
      this.$refs.tabs.setFinishCurrent(current);
      this.current = current;
      this.swiperCurrent = current;
      //切换状态重新请求
      // this.myOrder()
    },

    // scroll-view到底部加载更多
    onreachBottom() {
      console.log("到底部 加载更多");
      //请求订单
      this.myOrder();
    },

    //选择快递
    confirm1(e) {
      console.log(e, "1111");
      const { value, label } = e[0];
      console.log(value, "value");
      console.log(e, "选择器");
      this.formData.deliveryCompany = label;
      console.log(this.formData, "formData");
      this.type = "text";
    },

    //寄出快递
    expressDelivery(item, index, num) {
      console.log(item, "寄出快递");
      this.expressDeliveryList = { ...item, index, num };
      this.showToggle = true;
    },

    //填写售后信息确认
    async confirmInfo() {
      const { refundOrder } = this.expressDeliveryList;
      this.formData.afterSaleSn = refundOrder.afterSaleSn || "";
      this.formData.orderSn = refundOrder.orderSn || "";

      console.log(this.formData, "确认");
      if (!this.formData.deliveryCompany) {
        this.$util.Tips({
          title: "请选择快递公司!",
        });
        this.showToggle = true;
        return;
      } else if (!this.formData.deliverySn) {
        this.$util.Tips({
          title: "请填写物流单号!",
        });
        this.showToggle = true;
        return;
      }
      this.showToggle = false;
      const res = await saveDelivery(this.formData);
      console.log(res, "退款信息");
      if (res.code === 0) {
        uni.showToast({
          title: "提交成功",
          icon: "success",
          duration: 2000,
        });
      }
      console.log(this.formData, "确认");
    },

    //查看物流
    logisticsFn(item, index) {
      console.log(item, index, "查看物流");
      return;
      uni.navigateTo({
        url: `/pages/subpackage/logistics/index?order=${JSON.stringify(item)}`,
      });
    },

    //取消订单
    cancellationFn(item, index, num) {
      console.log(this.swiperCurrent, "this.swiperCurrent liang");
      if (num === "-1") {
        this.showModelContent = "是否确认删除订单？";
        this.showModel = true;
        this.orderUpdata = { ...item, index, num };
        return;
      }

      if (num === "-3") {
        this.showModelContent = "是否确认取消售后？";
        this.showModel = true;
        console.log(item, "售后");
        this.orderUpdata = { ...item, index, num };
        return;
      }

      this.orderUpdata = { ...item, index, num };
      console.log(this.orderUpdata, "orderUpdata 状态");
      console.log(this.orderFilter, "更新");
    },
    //弹窗确认按钮
    async confirm() {
      this.showModel = false;
      const { orderSn, status, id, index, num, confirmStatus, refundOrder } =
        this.orderUpdata;

      if (num === "-3") {
        const data = {
          orderSn: refundOrder.orderSn,
        };
        const res = await cancelApi(data);
        console.log(res, "取消退款");
        if (res.code === 0) {
          uni.showToast({
            title: `取消成功`,
            icon: "success",
            duration: 2000,
          });
          this.orderFilter.splice(index, 1);
          this.order.current = 1;
          this.orderFilter = [];
          this.myOrder();
        }
        return;
      }

      if (num === "-1") {
        //删除订单
        const res = await cancelDelete(refundOrder.orderSn);
        console.log(res, "删除订单");
        if (res.code === 0) {
          //根据index删除数组中取消的那一项
          this.orderFilter.splice(index, 1);
          uni.showToast({
            title: `删除成功`,
            icon: "success",
            duration: 2000,
          });
        }
        return;
      }
    },
  },
};
</script>

<style>
/* #ifndef H5 */
page {
  height: 100vh;
  background-color: #f2f2f2;
}
/* #endif */
</style>

<style lang="scss" scoped>
.slot-content {
  display: flex;
  padding: rpx(40) rpx(12);
  flex-direction: column;
  align-items: center;
  .input_wrapper {
    width: 100%;
    &:last-child {
      margin-top: rpx(20);
    }
  }
}

page {
  min-height: 100vh;
  background-color: #f2f2f2;
  overflow: auto;
}

.wrap {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: auto;
  width: 100%;
}

.swiper-box::v-deep {
  height: 100%;
  .swiper-item {
    //height: 1000px;
    //padding-top: rpx(12);
    height: 100vh;
    padding-bottom: rpx(16);
    .scroll_wrapper {
      height: 100% !important;
      background: #f5f5f5;
      //padding: rpx(12) rpx(12) rpx(0) rpx(12);
      view.order_wrapper {
        margin: rpx(8) auto rpx(8) auto;
        //margin-bottom: rpx(8);
        width: rpx(351);
        //height: rpx(191);
        background: #ffffff;
        border-radius: rpx(5);
        padding: rpx(12);
        .title_wrapper {
          display: flex;
          justify-content: space-between;
          margin-bottom: rpx(8);
          .left_ {
            display: flex;
            align-items: center;
            > image {
              width: rpx(14);
              height: rpx(14);
              margin-right: rpx(4);
              vertical-align: middle;
            }
            .text {
              font-size: rpx(13);
              font-weight: 400;
              color: #353535;
            }
          }
          .right_ {
            font-size: rpx(13);
            font-weight: bold;
            color: #fa5151;
          }
        }
        > .order_info_wrapper {
          display: flex;
          > image {
            width: rpx(72);
            height: rpx(72);
          }
          > .right_wrapper {
            flex: 1;
            margin-left: rpx(6);
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            > view {
              display: flex;
            }
            > .item_1 {
              justify-content: space-between;
              margin-bottom: rpx(3);
              view:first-child {
                //width: rpx(168);
                font-size: rpx(12);
                font-weight: 400;
                color: #353535;
                overflow: hidden;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2; /*最大行数*/
              }
              view:last-child {
                margin-left: rpx(5);
              }
            }
            > .item_2 {
              display: flex;
              margin-bottom: rpx(4);
              > view {
                //height: rpx(16);
                background: rgba(250, 81, 81, 0.1);
                border-radius: rpx(2);
                border: rpx(1) solid #fa5151;
                font-size: rpx(10);
                padding: rpx(1) rpx(3);
                font-weight: 400;
                color: #fa5151;
              }
            }
            > .item_3 {
              font-size: rpx(12);
              font-weight: 400;
              color: #888888;
              display: flex;
              align-items: center;
              justify-content: space-between;
            }
          }
        }
        > .money_wrapper {
          display: flex;
          margin-top: rpx(8);
          justify-content: space-between;
          > view {
            display: flex;
            color: #353535;
            font-size: rpx(12);
            view:first-child {
              margin-right: rpx(10);
            }
            view:last-child {
              > text {
                color: #fa5151;
              }
            }
          }
          > .left_ {
            font-size: rpx(13);
            font-weight: 400;
            color: #353535;
          }
        }
        > .but_wrapper {
          display: flex;
          margin-top: rpx(12);
          > view {
            display: flex;
            margin-left: auto;
            view {
              width: rpx(88);
              height: rpx(32);
              border-radius: rpx(16);
              border: rpx(1) solid #dddddd;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: rpx(15);
              font-weight: 400;
              color: #888888;
              &:not(:last-child) {
                margin-right: rpx(8);
              }
              &.success_wrapper {
                background: #1ab394;
                color: #ffffff;
                border: none;
              }
              &.cancelRefund {
                background: #fa9d3b;
                color: #ffffff;
                font-size: rpx(13);
                border: none;
              }

              &.error_wrapper {
                background: red;
                color: #ffffff;
                border: none;
              }
            }
            > .expressDelivery_ {
              color: #62bce3;
              border: rpx(1) solid #62bce3;
            }
            > .confirm_ {
              border: rpx(1) solid #fa5151;
              color: #fa5151;
            }
            > .payment_ {
              color: #ffffff;
              background: #fa5151;
            }
          }
        }
      }
    }
  }
}

/*修改tabs 的样式*/
.u-tabs-box::v-deep {
  .u-tabs {
    //background: pink !important;
    padding: rpx(0) rpx(6);
  }
}

.none_shopping {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  > text {
    font-size: rpx(13);
    font-weight: 400;
    color: #b2b2b2;
  }
  > image {
    width: rpx(222);
    height: rpx(158);
  }
}
</style>
